<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleDownload" class="custom-download-btn">
          下载
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-input v-model="searchKeyword" placeholder="请输入搜索关键词" clearable class="custom-input"></el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch" class="custom-search-btn">
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" class="custom-add-btn">
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="fenxiangList" class="custom-table" border resizable>
      <el-table-column v-for="(column, index) in tableColumns" :key="index" :label="column.label" :prop="column.prop" :formatter="column.formatter" :width="column.width">
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)" class="custom-edit-btn">
            编辑
          </el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)" class="custom-delete-btn">
            删除
          </el-button>
        </template>
      </el-table-column>
      <!-- 将是否超出检修时间的列移动到检修周期后面 -->
      <el-table-column label="是否超出检修时间" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.overdueDays > 0" style="color: red;">{{ scope.row.overdueDays }} 天</span>
          <span v-else-if="scope.row.overdueDays === 0">未超出</span>
          <span v-else></span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page.sync="currentPage" :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total" class="custom-pagination">
    </el-pagination>

    <el-dialog :title="isEdit? '编辑分享记录' : '新增分享记录'" :visible.sync="dialogVisible" width="50%" class="custom-dialog">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="站区名称" prop="zqname">
          <el-input v-model="form.zqname" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="设备名称" prop="equipname">
          <el-input v-model="form.equipname" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="检修日期" prop="mtdate">
          <el-date-picker v-model="form.mtdate" type="date" placeholder="选择检修日期" format="yyyy-MM-dd"
            value-format="yyyy-MM-dd" class="custom-datepicker"></el-date-picker>
        </el-form-item>
        <el-form-item label="检修周期" prop="maitaincycle">
          <el-input v-model.number="form.maitaincycle" class="custom-input"></el-input>
        </el-form-item>
        <!-- 将是否超出检修时间的输入框也移动到检修周期后面 -->
        <el-form-item label="是否超出检修时间" prop="overdueDays">
          <el-input v-model="form.overdueDays" disabled class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="开始杆号" prop="ganhaos">
          <el-input v-model="form.ganhaos" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="平滑过渡情况" prop="phgd">
          <el-input v-model="form.phgd" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="零部件情况" prop="lbj">
          <el-input v-model="form.lbj" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="mtdirector">
          <el-input v-model="form.mtdirector" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="检修操作者" prop="mtoperator">
          <el-input v-model="form.mtoperator" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="mtremark">
          <el-input v-model="form.mtremark" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="是否最新" prop="islast">
          <el-select v-model="form.islast" class="custom-select">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上行接头磨耗S" prop="sjtmss">
          <el-input v-model="form.sjtmss" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="上行接头磨耗X" prop="sjtmsx">
          <el-input v-model="form.sjtmsx" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="中部接头磨耗S" prop="zjtmss">
          <el-input v-model="form.zjtmss" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="中部接头磨耗X" prop="zjtmsx">
          <el-input v-model="form.zjtmsx" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="下行接头磨耗S" prop="xjtmss">
          <el-input v-model="form.xjtmss" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="下行接头磨耗X" prop="xjtmsx">
          <el-input v-model="form.xjtmsx" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="设备类型" prop="equiptype">
          <el-input v-model="form.equiptype" class="custom-input"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="custom-cancel-btn">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm" class="custom-confirm-btn">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  selectAll,
  deleteFenxiang,
  downloadFenxiang,
  addFenxiang,
  updateFenxiang
} from "@/api/MaintenanceRecord/fenxiang";
import dayjs from "dayjs";

export default {
  name: "FenxiangList",
  data() {
    return {
      loading: true,
      fenxiangList: [],
      allList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: "",
      tableColumns: [
        { label: "站区名称", prop: "zqname", width: "150" },
        { label: "设备名称", prop: "equipname", width: "180" },
        { label: "检修日期", prop: "mtdate", formatter: this.formatDate, width: "150" },
        { label: "检修周期", prop: "maitaincycle", width: "150" },
        { label: "是否超出检修时间", prop: "overdueDays", width: "120" },
        { label: "开始杆号", prop: "ganhaos", width: "120" },
        { label: "平滑过渡情况", prop: "phgd", width: "200" },
        { label: "零部件情况", prop: "lbj", width: "200" },
        { label: "负责人", prop: "mtdirector", width: "120" },
        { label: "检修操作者", prop: "mtoperator", width: "120" },
        { label: "备注", prop: "mtremark", width: "250" },
        { label: "是否最新", prop: "islast", width: "120" },
        { label: "上行接头磨耗S", prop: "sjtmss", width: "150" },
        { label: "上行接头磨耗X", prop: "sjtmsx", width: "150" },
        { label: "中部接头磨耗S", prop: "zjtmss", width: "150" },
        { label: "中部接头磨耗X", prop: "zjtmsx", width: "150" },
        { label: "下行接头磨耗S", prop: "xjtmss", width: "150" },
        { label: "下行接头磨耗X", prop: "xjtmsx", width: "150" },
        { label: "设备类型", prop: "equiptype", width: "180" }
      ],
      dialogVisible: false,
      isEdit: false,
      form: {
        zqname: "",
        equipname: "",
        mtdate: "",
        maitaincycle: null,
        overdueDays: "",
        ganhaos: "",
        phgd: "",
        lbj: "",
        mtdirector: "",
        mtoperator: "",
        mtremark: "",
        islast: null,
        sjtmss: "",
        sjtmsx: "",
        zjtmss: "",
        zjtmsx: "",
        xjtmss: "",
        xjtmsx: "",
        equiptype: ""
      },
      rules: {
        zqname: [
          { required: true, message: "请输入站区名称", trigger: "blur" }
        ],
        equipname: [
          { required: true, message: "请输入设备名称", trigger: "blur" }
        ],
        mtdate: [
          { required: true, message: "请选择检修日期", trigger: "blur" }
        ],
        maitaincycle: [
          { required: true, message: "请输入检修周期", trigger: "blur" }
        ],
        ganhaos: [
          { required: true, message: "请输入开始杆号", trigger: "blur" }
        ],
        phgd: [
          { required: true, message: "请输入平滑过渡情况", trigger: "blur" }
        ],
        lbj: [
          { required: true, message: "请输入零部件情况", trigger: "blur" }
        ],
        mtdirector: [
          { required: true, message: "请输入负责人", trigger: "blur" }
        ],
        mtoperator: [
          { required: true, message: "请输入检修操作者", trigger: "blur" }
        ],
        mtremark: [
          { required: true, message: "请输入备注", trigger: "blur" }
        ],
        islast: [
          { required: true, message: "请选择是否最新", trigger: "blur" }
        ],
        sjtmss: [
          { required: true, message: "请输入上行接头磨耗S", trigger: "blur" }
        ],
        sjtmsx: [
          { required: true, message: "请输入上行接头磨耗X", trigger: "blur" }
        ],
        zjtmss: [
          { required: true, message: "请输入中部接头磨耗S", trigger: "blur" }
        ],
        zjtmsx: [
          { required: true, message: "请输入中部接头磨耗X", trigger: "blur" }
        ],
        xjtmss: [
          { required: true, message: "请输入下行接头磨耗S", trigger: "blur" }
        ],
        xjtmsx: [
          { required: true, message: "请输入下行接头磨耗X", trigger: "blur" }
        ],
        equiptype: [
          { required: true, message: "请输入设备类型", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    filteredList() {
      if (!this.searchKeyword) return this.allList;
      const keyword = this.searchKeyword.toLowerCase();
      return this.allList.filter(item =>
        Object.values(item).some(value =>
          String(value).toLowerCase().includes(keyword)
        )
      );
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const params = {};
      if (this.searchKeyword) {
        params.searchKeyword = this.searchKeyword;
      }
      selectAll(params)
     .then((response) => {
          this.allList = response.data;
          this.allList.forEach(item => {
            const today = dayjs();
            const mtdate = dayjs(item.mtdate);
            const maitaincycleInDays = item.maitaincycle * 30; // 将月转换为天
            const diff = today.diff(mtdate, 'day');
            item.overdueDays = diff - maitaincycleInDays;
          });
          this.total = this.allList.length;
          this.currentPage = 1;
          this.updateFenxiangList();
          this.loading = false;
        })
     .catch((error) => {
          console.error("接口请求出错:", error);
          this.loading = false;
        });
    },
    updateFenxiangList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.fenxiangList = this.filteredList.slice(start, end);
    },
    handleDelete(row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
     .then(() => {
          deleteFenxiang(row.recordid)
       .then(() => {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.fetchData();
              })
       .catch((error) => {
                console.error("删除失败:", error);
                this.$message({
                  type: "error",
                  message: "删除失败"
                });
              });
        })
     .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateFenxiangList();
    },
    handleDownload() {
      downloadFenxiang()
     .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "分享记录数据.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
     .catch((error) => {
          console.error("下载失败:", error);
        });
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    formatDate(row, column, cellValue, index) {
      return dayjs(cellValue).format("YYYY-MM-DD");
    },
    handleEdit(row) {
      this.isEdit = true;
      this.form = {...row };
      this.dialogVisible = true;
    },
    handleAdd() {
      this.isEdit = false;
      this.form = {
        zqname: "",
        equipname: "",
        mtdate: "",
        maitaincycle: null,
        overdueDays: "",
        ganhaos: "",
        phgd: "",
        lbj: "",
        mtdirector: "",
        mtoperator: "",
        mtremark: "",
        islast: null,
        sjtmss: "",
        sjtmsx: "",
        zjtmss: "",
        zjtmsx: "",
        xjtmss: "",
        xjtmsx: "",
        equiptype: ""
      };
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            updateFenxiang(this.form.recordid, this.form)
           .then(() => {
                this.$message.success("编辑成功");
                this.fetchData();
                this.dialogVisible = false;
              })
           .catch((error) => {
                console.error("编辑失败:", error);
                this.$message.error("编辑失败");
              });
          } else {
            addFenxiang(this.form)
           .then(() => {
                this.$message.success("新增成功");
                this.fetchData();
                this.dialogVisible = false;
              })
           .catch((error) => {
                console.error("新增失败:", error);
                this.$message.error("新增失败");
              });
          }
        } else {
          this.$message.warning("请填写所有必填字段");
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.custom-table {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }
.custom-table.el-table__header th {
    background-color: #f5f7fa;
    color: #303133;
    font-weight: bold;
  }
.custom-table.el-table__body tr {
    height: 40px;
  }
.custom-table.el-table__body td {
    color: #606266;
  }
.custom-download-btn {
    background-color: #67c23a;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-download-btn:hover {
    background-color: #85ce61;
  }
.custom-search-btn,.custom-add-btn {
    background-color: #409EFF;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-search-btn:hover,.custom-add-btn:hover {
    background-color: #66b1ff;
  }
.custom-input {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-input:hover,.custom-input:focus {
    border-color: #409EFF;
  }
.custom-edit-btn,.custom-delete-btn {
    color: #409EFF;
  }
.custom-edit-btn:hover,.custom-delete-btn:hover {
    color: #66b1ff;
  }
.custom-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
.custom-pagination.el-pagination button,.custom-pagination.el-pagination span {
    font-size: 14px;
    color: #606266;
  }
.custom-pagination.el-pagination.el-pager li {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin: 0 5px;
  }
.custom-pagination.el-pagination.el-pager li:hover {
    color: #409EFF;
    border-color: #409EFF;
  }
.custom-dialog {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #fff;
  }
.custom-datepicker {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-datepicker:hover,.custom-datepicker:focus {
    border-color: #409EFF;
  }
.custom-select {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    background-color: #f5f7fa;
  }
.custom-select:hover,.custom-select:focus {
    border-color: #409EFF;
  }
.custom-cancel-btn {
    background-color: #e4e7ed;
    color: #606266;
    border: none;
    border-radius: 4px;
  }
.custom-cancel-btn:hover {
    background-color: #d1dbe5;
  }
.custom-confirm-btn {
    background-color: #409EFF;
    color: #fff;
    border: none;
    border-radius: 4px;
  }
.custom-confirm-btn:hover {
    background-color: #66b1ff;
  }
</style>